package weaver.jobs.zkwz.duss;

import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.resource.ResourceComInfo;
import weaver.interfaces.schedule.BaseCronJob;
import weaver.soa.workflow.request.MainTableInfo;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;
import weaver.soa.workflow.request.RequestService;
import weaver.workflow.request.RequestComInfo;
import weaver.workflow.workflow.WorkflowComInfo;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Title: ecology
 * @Company: 泛微软件
 * @author: weaver.Dusongsong
 * @version: 1.0
 * @CreateDate: 2022-12-06
 * @Description: 、试用期分为3个月和6个月的，试用期考核指标书流程触发的时间:3个月的:入职第一天触发第1个考核，第三个月的第一天触发第二个新的考核；
 * 6个月:入职第一天触发第 1 个考核，第四个月的第一天触发第二个新的考核
 * @ModifyLog:
 **/

public class WeSyqkhzbsCronJob extends BaseCronJob {

    @Override
    public void execute() {
        BaseBean baseBean = new BaseBean();
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        try {
            String currentDate = DateUtil.getCurrentDate();
            ResourceComInfo resourceComInfo = new ResourceComInfo();
            baseBean.writeLog(">>>>>>WeSyqkhzbsCronJob>>>>currentDate" + currentDate);
            //入职第一天触发第1个考核
            String sql = "select t.id,t.probationenddate,t.jobtitle,t.workcode,t.departmentid from hrmresource t " +
                    "join cus_fielddata t1 on t.id=t1.id " +
                    "where t.status=0 and t.companystartdate=? and ifnull(t.numberfield5,0)=0 and ifnull(t.loginid,'') !='' " +
                    "and t1.scopeid=3 and t1.scope='HrmCustomFieldByInfoType' and t1.field14 !=2";
            rs.executeQuery(sql,currentDate);
            while (rs.next()) {
                Map<String, String> requestMainMap = new HashMap<>();
                //userid
                String id = Util.null2String(rs.getString("id"));
                //试用期结束日期
                String probationenddate = Util.null2String(rs.getString("probationenddate"));
                String jobtitle = Util.null2String(rs.getString("jobtitle"));
                String workcode = Util.null2String(rs.getString("workcode"));
                String departmentid = Util.null2String(rs.getString("departmentid"));
                String requestName = "试用期考核指标书-" + resourceComInfo.getLastname(id) + "-" + currentDate;
                baseBean.writeLog(">>>>>>WeSyqkhzbsCronJob>>>>requestName1=" + requestName);
                requestMainMap.put("sqr", id);
                requestMainMap.put("gh", workcode);
                requestMainMap.put("sqrbm", departmentid);
                requestMainMap.put("sqrq", currentDate);
                requestMainMap.put("zw", jobtitle);
                requestMainMap.put("syqsj", probationenddate);
                boolean status = WorkflowCreate(id, requestName, requestMainMap);
                baseBean.writeLog(">>>>>>WeSyqkhzbsCronJob>>>>status=" + status);
                if (status) {
                    rs1.executeUpdate("update cus_fielddata set field44=1 where id=? and t1.scopeid=3 and t1.scope='HrmCustomFieldByInfoType'", id);
                }
            }
            //触发第二个新的考核
            sql = "select t.id,t.companystartdate,t.probationenddate,t.jobtitle,t.workcode,t.departmentid from hrmresource t " +
                    "join cus_fielddata t1 on t.id=t1.id " +
                    "where t.status=0 and t.companystartdate=? and ifnull(t.numberfield5,0)=0 and ifnull(t.loginid,'') !='' " +
                    "and t1.scopeid=3 and t1.scope='HrmCustomFieldByInfoType' and t1.field44 =1";
            rs.executeQuery(sql);
            while (rs.next()) {
                Map<String, String> requestMainMap = new HashMap<>();
                //userid
                String id = Util.null2String(rs.getString("id"));
                //试用期结束日期
                String companystartdate = Util.null2String(rs.getString("companystartdate"));
                String probationenddate = Util.null2String(rs.getString("probationenddate"));
                baseBean.writeLog(">>>>>>WeSyqkhzbsCronJob>>>>入职日期=" + companystartdate + ",试用结束日期=" + probationenddate);
                int syzq = getResourceSyzq(id);
                if (syzq < 0) {
                    baseBean.writeLog(">>>>>>WeSyqkhzbsCronJob>>>>试用周期=" + syzq);
                } else {
                    baseBean.writeLog(">>>>>>WeSyqkhzbsCronJob>>>>试用周期=" + syzq);
                    String executeDate = "";
                    if (syzq == 0) {
                        //试用期为3个月
                        String twoDate = addMonthFormat(companystartdate, 2);
                        executeDate = DateUtil.addDate(twoDate, 1);
                    }
                    if (syzq == 1) {
                        //试用期为6个月
                        String fourDate = addMonthFormat(companystartdate, 3);
                        executeDate = DateUtil.addDate(fourDate, 1);
                    }
                    baseBean.writeLog(">>>>>>WeSyqkhzbsCronJob>>>>executeDate=" + executeDate);
                    if (DateUtil.compDate(executeDate, currentDate) == 0) {
                        String jobtitle = Util.null2String(rs.getString("jobtitle"));
                        String workcode = Util.null2String(rs.getString("workcode"));
                        String departmentid = Util.null2String(rs.getString("departmentid"));
                        String requestName = "试用期考核指标书-" + resourceComInfo.getLastname(id) + "-" + currentDate;
                        baseBean.writeLog(">>>>>>WeSyqkhzbsCronJob>>>>requestName2=" + requestName);
                        requestMainMap.put("sqr", id);
                        requestMainMap.put("gh", workcode);
                        requestMainMap.put("sqrbm", departmentid);
                        requestMainMap.put("sqrq", currentDate);
                        requestMainMap.put("zw", jobtitle);
                        requestMainMap.put("syqsj", probationenddate);
                        boolean status = WorkflowCreate(id, requestName, requestMainMap);
                        if (status) {
                            rs1.executeUpdate("update cus_fielddata set field44=2 where id=? and t1.scopeid=3 and t1.scope='HrmCustomFieldByInfoType'", id);
                        }
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 日期加上几个月
     */
    public static boolean WorkflowCreate(String id, String requestName, Map<String, String> requestMainMap) {
        String workflowid =  getWorkflowId("-45");
        String newrequestid = WorkflowCreateByRequestMap(id, workflowid, requestName, "0", requestMainMap);
        return Util.getIntValue(newrequestid) > 0;
    }
    /**
     * 获取生效版本的workflowID
     *
     * @param formid
     * @return
     */
    public static String getWorkflowId(String formid) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select ifnull(activeVersionID,id) from workflow_base where formid=? group by ifnull(activeVersionID,id)", formid);
        rs.next();
        return Util.null2String(rs.getString(1));
    }
    /**
     * 日期加上几个月
     *
     * @param dateParem
     * @param day
     * @return
     */
    public static String addMonthFormat(String dateParem, int day) {
        Calendar calendar = DateUtil.addMonth(DateUtil.getCalendar(dateParem), day);
        Date date = calendar.getTime();
        //格式化日期格式
        return new SimpleDateFormat("yyyy-MM-dd").format(date);
    }

    /**
     * @param @param  creatorId    创建人Id
     * @param @param  workflowId   流程Id
     * @param @param  requestName  请求标题
     * @param @param  IsNextFlow   是否提交到下一节点
     * @param @param  requestMap   Map格式的主表数据<fieldname,fieldvalue>=<字段名称,字段值>
     * @param @return 设定文件
     * @return String    返回类型
     * @throws
     * @Title: WorkflowCreateByMainTableMap
     */
    public static String WorkflowCreateByRequestMap(String creatorId, String workflowId, String requestName, String IsNextFlow, Map<String, String> requestMainMap) {
        BaseBean baseBean = new BaseBean();
        baseBean.writeLog("-----创建流程传递的参数个数--------");
        baseBean.writeLog("creatorId:" + creatorId);
        baseBean.writeLog("workflowId:" + workflowId);
        baseBean.writeLog("requestName:" + requestName);
        baseBean.writeLog("IsNextFlow:" + IsNextFlow);

        String requestid = "";
        RequestInfo requestInfo = new RequestInfo();
        requestInfo.setCreatorid(creatorId);
        requestInfo.setWorkflowid(workflowId);
        requestInfo.setDescription(requestName);
        if ("0".equals(IsNextFlow)) {
            requestInfo.setIsNextFlow(IsNextFlow);
        }

        //主表字段
        MainTableInfo mainTableInfo = new MainTableInfo();
        Property[] propertyArray = new Property[requestMainMap.size()];
        int p = 0;
        for (Map.Entry<String, String> entry : requestMainMap.entrySet()) {
            propertyArray[p] = new Property();
            propertyArray[p].setName(Util.null2String(entry.getKey()));
            propertyArray[p].setValue(Util.null2String(entry.getValue()));
            baseBean.writeLog("\r\n---p=" + p + "---Key=" + entry.getKey() + "---Value=" + entry.getValue());
            p++;
        }
        baseBean.writeLog("-----创建流程传递的参数个数p=" + p);
        mainTableInfo.setProperty(propertyArray);
        requestInfo.setMainTableInfo(mainTableInfo);
        RequestService service = new RequestService();
        try {
            //流程
            try {
                requestid = service.createRequest(requestInfo);
            } catch (Exception e) {
                baseBean.writeLog("=======" + e.getMessage());
            }
            //String userId = requestInfo.getLastoperator();//请求最后的操作者
            //记录日志
            StringBuffer sbf = new StringBuffer("\r\n-----xwd创建工作流记录日志开始");
            WorkflowComInfo wfcif = new WorkflowComInfo();
            RequestComInfo rcif = new RequestComInfo();
            ResourceComInfo rscif = new ResourceComInfo();
            sbf.append("\r\n-----姓名:" + rscif.getLastname(rcif.getRequestCreater(requestid)));
            sbf.append("\r\n-----时间:" + rcif.getRequestCreateTime(requestid));
            sbf.append("\r\n-----创建流程:" + wfcif.getWorkflowname(workflowId));
            sbf.append("\r\n-----请求:" + rcif.getRequestname(requestid));
            sbf.append("\r\n-----请求:" + requestid);
            sbf.append("\r\n-----创建工作流记录日志结束");
            baseBean.writeLog(sbf.toString());
            System.out.println("" + sbf.toString());
        } catch (Exception e) {
            baseBean.writeLog("错误：" + e);
            System.out.println("错误：" + e);
        }
        return requestid;
    }

    /**
     * 获取人员试用周期
     *
     * @param resourceid
     * @return
     */
    public static int getResourceSyzq(String resourceid) {
        RecordSet rs = new RecordSet();
        rs.executeQuery(" select field14 from cus_fielddata where scope='HrmCustomFieldByInfoType' and SCOPEID=3 and id=?", resourceid);
        rs.next();
        return Util.getIntValue(rs.getString(1));
    }

}

